<?php

class Application_Model_UsersMapper {

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Users');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_Users $users) {

        $errors = array();

        $data = array(
            'email' => $users->getEmail(),
            'paswd' => $users->getPaswd(),
        );

        if (Zend_Validate::is($data['email'], 'EmailAddress')) {

            $result = $this->findByEmail($data['email']);

            if ($result != false) {

                $errors[] = "An account using this e-mail address already exists.".$result;
            }

        } else {

            $errors[] = "Please provide a valid e-mail address.";
        }

        $valid_pswd = new Zend_Validate_StringLength(6, 20);

        if (!$valid_pswd->isValid($data['pswd'])) {

            $errors[] = "Your password must be 6-20 characters.";
        }

        if (count($errors) == 0) {

             unset($data['id']);
            $this->getDbTable()->insert($data);

        }


    }

    public function findByEmail($email){

        $result = $this->getDbTable()->find($email);
        if (0 == count($result)) {
            return 0;
        }
        $row = $result->current();
        return $row->id;

    }


}

